package com.web.nyist.controller.admin.auth;

import com.google.common.collect.Lists;
import com.web.nyist.common.Constant;
import com.web.nyist.controller.admin.AdminController;
import com.web.nyist.dto.JSONResponse;
import com.web.nyist.dto.admin.AdminMenuButtonDto;
import com.web.nyist.dto.admin.AdminRoleDto;
import com.web.nyist.dto.admin.AdminUserDto;
import com.web.nyist.dto.admin.DataGridPageDto;
import com.web.nyist.model.AdminRole;
import com.web.nyist.model.AdminUser;
import com.web.nyist.service.AdminService;
import com.web.nyist.service.db.AdminRoleService;
import com.web.nyist.service.db.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * Created by penghuiping on 2/21/15.
 */
@Controller
@RequestMapping(UserController.BASE_URL)
public class UserController extends AdminController {

    public static final String BASE_URL = "/admin/auth/user/";

    @Autowired
    AdminUserService adminUserService;

    @Autowired
    AdminRoleService adminRoleService;

    @Autowired
    AdminService adminService;

    @RequestMapping(value = "index.do")
    public ModelAndView index(ModelAndView modelAndView, Long id, HttpServletRequest request) throws Throwable {
        AdminUserDto user = (AdminUserDto) request.getSession().getAttribute(Constant.SESSION_USER);
        List<AdminRole> roles = (List<AdminRole>) adminRoleService.findAllEnabled();
        AdminMenuButtonDto adminMenuButtonDto = adminService.findOneMenuAndButtonById(user.getMenus(), id);
        modelAndView.addObject("buttons", adminMenuButtonDto.getChildren());
        modelAndView.addObject("roles", AdminRoleDto.from(roles));
        modelAndView.setViewName(BASE_URL + "index.htm");
        return modelAndView;
    }


    @RequestMapping(value = "query.do")
    public
    @ResponseBody
    DataGridPageDto query(Integer rows, Integer page, final String searchParams) throws Throwable {
        if (null == page) page = Constant.PAGE_FIRST;
        if (null == rows) rows = Constant.PAGE_SIZE;
        PageRequest pageRequest = new PageRequest(page - 1, rows, Sort.Direction.DESC, "id");
        DataGridPageDto<AdminUser> dataGridPageDto = adminUserService.query(page, rows, searchParams);
        //转换成dto输出
        DataGridPageDto<AdminUserDto> adminUserDtoDataGridPageDto = new DataGridPageDto<AdminUserDto>();
        adminUserDtoDataGridPageDto.setRows(AdminUserDto.from(dataGridPageDto.getRows()));
        adminUserDtoDataGridPageDto.setTotal(dataGridPageDto.getTotal());
        return adminUserDtoDataGridPageDto;
    }

    @RequestMapping(value = "edit.do")
    public
    @ResponseBody
    AdminUserDto edit(Long id) throws Throwable {
        AdminUser user = adminUserService.findOne(id);
        AdminUserDto userDto = new AdminUserDto(user);
        return userDto;
    }


    @RequestMapping(value = "delete.do")
    public
    @ResponseBody
    JSONResponse delete(Long ids[]) throws Throwable {
        List<AdminUser> users = (List<AdminUser>) adminUserService.findAll(Lists.newArrayList(ids));
        adminUserService.delete(users);
        return succeed(true);
    }

    @RequestMapping(value = "editSubmit.do")
    public
    @ResponseBody
    JSONResponse editSubmit(@Valid AdminUserDto user, Errors errors) throws Throwable {
        if (errors.hasErrors()) {
            return failed("出错啦！");
        }
        if (null != user.getId() && user.getId() > 0) {
            AdminUser temp = adminUserService.findOne(user.getId());
            temp.setUsername(user.getUsername());
            temp.setEmail(user.getEmail());
            temp.setEnable(user.getEnable());
            temp.setUpdateTime(new Date());
            temp.setRole(user.getRole().toModel());
            adminUserService.save(temp);
        } else {
            user.setCreateTime(new Date());
//            String pass = new String(DigestUtil.bytes2hex(DigestUtil.MD5(user.getPassword())));
//            user.setPassword(pass);
            adminUserService.save(user.toModel());
        }
        return succeed(true);
    }
}
